package com.fizzkai.p2p.bussness.service.impl;

import com.fizzkai.p2p.bussness.domain.ExpAccount;
import com.fizzkai.p2p.bussness.domain.ExpAccountGrantRecord;
import com.fizzkai.p2p.bussness.mapper.ExpAccountMapper;
import com.fizzkai.p2p.bussness.service.IExpAccountFlowService;
import com.fizzkai.p2p.bussness.service.IExpAccountGrantRecordService;
import com.fizzkai.p2p.bussness.service.IExpAccountService;
import com.fizzkai.p2p.core.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service@Transactional
public class ExpAccountServiceImpl implements IExpAccountService {

    @Autowired
    private ExpAccountMapper expAccountMapper;
    @Autowired
    private IExpAccountGrantRecordService grantRecordService;
    @Autowired
    private IExpAccountFlowService expAccountFlowService;

    @Override
    public int save(ExpAccount entity) {
        return expAccountMapper.insert(entity);
    }

    @Override
    public int update(ExpAccount entity) {
        int row = expAccountMapper.updateByPrimaryKey(entity);
        AssertUtil.updateNotZero(row);
        return row;
    }

    @Override
    public ExpAccount get(Long id) {
        return expAccountMapper.selectByPrimaryKey(id);
    }

    @Override
    public void grantExpMoney(Long id, BigDecimal money, LastTime lastTime, int expmoneyType) {
        Date now = new Date();
        // 创建 发放记录
        ExpAccountGrantRecord record = new ExpAccountGrantRecord();
        record.setGrantUserId(id);
        record.setState(ExpAccountGrantRecord.STATE_NORMAL);
        record.setAmount(money);
        record.setGrantDate(now);
        record.setGrantType(expmoneyType);
        record.setReturnDate(lastTime.getReturnDate(now));
        record.setNote("注册发放体验金");
        grantRecordService.save(record);
        // 更新 账户
        ExpAccount expAccount = this.get(id);
        expAccount.setUsableAmount(expAccount.getUsableAmount().add(money));
        this.update(expAccount);
        // 增加流水
        expAccountFlowService.createRigisterFlow(expAccount, money);
    }


}
